package com.colorlight.cloud.gateway.api.message.interceptor.trans.impl;

import com.colorlight.cloud.gateway.api.exception.ReflexException;
import com.colorlight.cloud.gateway.api.message.interceptor.trans.TransToProtoInterceptor;
import com.colorlight.cloud.gateway.api.message.utils.BaseType;
import com.google.protobuf.Message;

import java.lang.reflect.*;

/**
 * 八个基本类型 以及 String 过滤器
 *
 * @author Demon
 * @date 18/12/2023 下午4:48
 */
public class BaseTypeTransToProtoInterceptor implements TransToProtoInterceptor {
	
	@Override
	public Boolean isInterceptor(Class<?> aClass) {
		return BaseType.isContains(aClass);
	}
	
	@Override
	public void addAttribute(
			Message.Builder builder, Object value, Class<?> inputClass, String methodName) {
		// 获取方法
		Method method = null;
		try {
			// 只需要一个参数
			method = builder.getClass().getMethod(methodName, inputClass);
		} catch (NoSuchMethodException e) {
			throw new ReflexException("获取方法失败");
		}
		// 方法调用
		try {
			method.invoke(builder, value);
		} catch (IllegalAccessException | InvocationTargetException e) {
			throw new ReflexException("获取方法失败");
		}
	}
	
	@Override
	public Class<?> getInputClass(Field field) {
		return BaseType.convert(field.getType());
	}
}
